<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryFormRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="店铺名称" prop="shopName">
        <el-input
          v-model="queryParams.shopName"
          placeholder="请输入店铺名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
        <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          :icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:shopItem:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          :icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:shopItem:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          :icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:shopItem:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          :icon="Download"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['system:shopItem:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="shopItemList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="店铺名称" align="center" prop="shopName" />
      <el-table-column label="地址" align="center" prop="address" />
      <el-table-column label="联系人" align="center" prop="contact" />
      <el-table-column label="联系电话" align="center" prop="phone" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          {{ (sysYesNo.find(i => i.value === String(scope.row.status)) || {}).label || scope.row.status }}
        </template>
      </el-table-column>
      <el-table-column label="添加时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            type="text"
            :icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:shopItem:edit']"
          >修改</el-button>
          <el-button
            type="text"
            :icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:shopItem:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      v-model:total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改门店对话框 -->
    <el-dialog :title="title" v-model="open" width="860px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="16">
          <el-col :span="24">
            <el-form-item label="门店名称" prop="shopName" required>
              <el-input v-model="form.shopName" placeholder="请输入店铺名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="主管人员" prop="managerId" required>
              <el-select v-model="form.managerId" placeholder="请输入主管名称" filterable clearable style="width: 100%">
                <el-option v-for="u in consultantOptions" :key="u.value" :label="u.label" :value="u.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="phone" required>
              <el-input v-model="form.phone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="详细地址" prop="address" required>
              <el-input v-model="form.address" placeholder="请输入地址" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-card shadow="never" style="margin-bottom: 12px">
          <template #header>
            <div>上架项目</div>
          </template>
          <el-row style="font-weight: 600; color: var(--el-text-color-primary); padding: 4px 8px;">
            <el-col :span="12">项目名称</el-col>
            <el-col :span="12">顾问配置</el-col>
          </el-row>
          <div style="max-height: 360px; overflow:auto; padding: 4px 0;">
            <el-row v-for="it in projectOptions" :key="it.value" :gutter="8" style="padding: 6px 8px;">
              <el-col :span="12">
                <el-checkbox v-model="selectedItems[it.value]">{{ it.label }}</el-checkbox>
              </el-col>
              <el-col :span="12">
                <el-select v-model="consultantMapping[it.value]" placeholder="请选择" clearable filterable style="width: 100%">
                  <el-option v-for="u in consultantOptions" :key="u.value" :label="u.label" :value="u.value" />
                </el-select>
              </el-col>
            </el-row>
          </div>
        </el-card>

        <el-form-item label="状态" prop="status" required>
          <el-radio-group v-model="form.status">
            <el-radio v-for="d in sysYesNo" :key="d.value" :value="d.value">{{ d.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ShopItem">
import { ref, reactive, toRefs } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Edit, Delete, Download } from '@element-plus/icons-vue'
import { listShopItem, getShopItem, delShopItem, addShopItem, updateShopItem, exportShopItem } from "@/api/system/shopIndex";
import { listShopItem as listProjectItems } from '@/api/system/shopItem'
import { getsysYesNo } from '@/api/system/goodType'
import { parseTime } from '@/utils/ruoyi'
import { download } from '@/utils/request'

const queryFormRef = ref()
const formRef = ref()
const sysYesNo = ref([])
// 顾问与项目选项，以及勾选/映射容器
const consultantOptions = ref([])
const projectOptions = ref([])
const selectedItems = reactive({})
const consultantMapping = reactive({})
const state = reactive({
  // 遮罩层
  loading: true,
  // 导出遮罩层
  exportLoading: false,
  // 选中数组
  ids: [],
  // 非单个禁用
  single: true,
  // 非多个禁用
  multiple: true,
  // 显示搜索条件
  showSearch: true,
  // 总条数
  total: 0,
  // 门店表格数据
  shopItemList: [],
  // 弹出层标题
  title: "",
  // 是否显示弹出层
  open: false,
  // 查询参数
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    shopName: null,
    address: null,
    contact: null,
    phone: null,
    status: null,
    createTime: null,
  },
  // 表单参数
  form: {},
  // 表单校验
  rules: {
    shopName: [{ required: true, message: '门店名称不能为空', trigger: 'blur' }],
    managerId: [{ required: true, message: '主管人员不能为空', trigger: 'change' }],
    phone: [{ required: true, message: '联系方式不能为空', trigger: 'blur' }],
    address: [{ required: true, message: '详细地址不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '请选择状态', trigger: 'change' }]
  }
})

const { loading, exportLoading, showSearch, total, shopItemList, title, open, queryParams, form, rules, single, multiple } = toRefs(state)

/** 查询门店列表 */
function getList() {
  loading.value = true
  listShopItem(queryParams.value).then(response => {
    shopItemList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}

/** 表单重置 */
function reset() {
  form.value = {
    id: null,
    shopName: null,
    managerId: null,
    address: null,
    contact: null,
    phone: null,
    status: "0",
    createTime: null,
    createBy: null,
    updateTime: null,
    updateBy: null
  }
  formRef.value?.resetFields()
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  queryFormRef.value?.resetFields()
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  state.ids = selection.map(item => item.id)
  state.single = selection.length!==1
  state.multiple = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  loadProjects()
  open.value = true
  title.value = "添加门店"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const id = row.id || state.ids[0]
  Promise.all([
    getShopItem(id),
    loadProjects()
  ]).then(([response]) => {
    form.value = response.data
    open.value = true
    title.value = "修改门店"
  })
}

/** 提交按钮 */
function submitForm() {
  formRef.value?.validate(valid => {
    if (valid) {
      const formData = { ...form.value }
      if (form.value.id != null) {
        updateShopItem(formData).then(response => {
          ElMessage.success("修改成功")
          open.value = false
          getList()
        })
      } else {
        addShopItem(formData).then(response => {
          ElMessage.success("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const ids = row.id || state.ids
  ElMessageBox.confirm('是否确认删除门店编号为"' + ids + '"的数据项?', "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    return delShopItem(ids)
  }).then(() => {
    getList()
    ElMessage.success("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  const queryParams = { ...state.queryParams }
  ElMessageBox.confirm('是否确认导出所有门店数据项?', "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    state.exportLoading = true
    return exportShopItem(queryParams)
  }).then(response => {
    download(response.msg)
    state.exportLoading = false
  }).catch(() => {})
}

// 加载字典并再拉取列表
function loadDicts() {
  return getsysYesNo().then(res => {
    const arr = res?.data || []
    sysYesNo.value = arr.map(p => ({ label: p.dictLabel, value: String(p.dictValue) }))
  }).catch(() => { sysYesNo.value = [] })
}

// 加载项目列表（上架项目）
function loadProjects() {
  return listProjectItems({ pageNum: 1, pageSize: 999 }).then(res => {
    const rows = res?.rows || []
    projectOptions.value = rows.map(r => ({ label: r.itemName, value: String(r.id) }))
  })
}

loadDicts().then(() => getList())
</script>